package com.yuchen.ishop.web.mytags;


import com.yuchen.ishop.Gobals;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.UUID;

/**
 * crsf
 */
public class TokenTag extends TagSupport {

    private boolean input = true;

    public void setInput(boolean input) {
        this.input = input;
    }

    @Override
    public int doStartTag() throws JspException {
        try {
            HttpSession session = pageContext.getSession();
            session.setAttribute(Gobals.CRSF_ID, null);
            String token = UUID.randomUUID().toString();
            session.setAttribute(Gobals.CRSF_ID, token);
            StringBuffer sb = new StringBuffer();
            if (input) {
                sb.append("<input");
                sb.append(" type=\"" + "hidden" + "\"");
                sb.append(" name=\"" + "crsf_token" + "\"");
                sb.append(" value=\"" + token + "\"");
                sb.append(" />");
            } else {
                sb.append(token);
            }

            pageContext.getOut().println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取标签体对象
        /*JspFragment body = this.getJspBody();
        body.invoke(null);*/
        return SKIP_BODY;
    }

    @Override
    public int doEndTag() throws JspException {

        return EVAL_PAGE;

    }


}
